package com.minidb.engine;

import java.io.*;
import java.util.*;
import com.minidb.sql_compliler.ASTNode.ColumnDef;

public class CatalogManager {
    private static final String CATALOG_FILE = "catalog.dat";
    private Map<String, List<ColumnDef>> tables = new HashMap<>();

    public CatalogManager() {
        loadCatalog();
    }

    // 新建表
    public void createTable(String tableName, List<ColumnDef> columns) {
        if (tables.containsKey(tableName)) {
            throw new RuntimeException("Table already exists: " + tableName);
        }
        tables.put(tableName, columns);
        saveCatalog();
    }

    // 获取表定义
    public List<ColumnDef> getTable(String tableName) {
        if (!tables.containsKey(tableName)) {
            throw new RuntimeException("Table does not exist: " + tableName);
        }
        return tables.get(tableName);
    }

    // --- 内部方法 ---

    private void loadCatalog() {
        File file = new File(CATALOG_FILE);
        if (!file.exists()) return;

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\|");
                if (parts.length != 2) continue;

                String tableName = parts[0];
                String[] cols = parts[1].split(",");
                List<ColumnDef> columnDefs = new ArrayList<>();
                for (String col : cols) {
                    String[] kv = col.split(":");
                    if (kv.length == 2) {
                        columnDefs.add(new ColumnDef(kv[0], kv[1]));
                    }
                }
                tables.put(tableName, columnDefs);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveCatalog() {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(CATALOG_FILE))) {
            for (Map.Entry<String, List<ColumnDef>> entry : tables.entrySet()) {
                String tableName = entry.getKey();
                List<ColumnDef> cols = entry.getValue();

                StringBuilder sb = new StringBuilder();
                sb.append(tableName).append("|");
                for (int i = 0; i < cols.size(); i++) {
                    ColumnDef col = cols.get(i);
                    sb.append(col.name).append(":").append(col.dataType);
                    if (i < cols.size() - 1) sb.append(",");
                }
                bw.write(sb.toString());
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
